<template>
  <div class="ai-analysis-page">
    <div class="page-header">
      <h3>智能数据分析</h3>
      <el-button type="primary" @click="showQueryDialog = true" :icon="Search">
        智能查询
      </el-button>
    </div>

    <div class="analysis-container">
      <!-- 左侧：查询区域 -->
      <div class="query-panel">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>数据分析助手</span>
              <el-button text @click="clearHistory" :icon="Delete">清空</el-button>
            </div>
          </template>
          
          <div class="query-input">
            <el-input
              v-model="queryText"
              type="textarea"
              :rows="4"
              placeholder="例如：分析最近一个月的销售趋势..."
              @keydown.ctrl.enter="executeQuery"
            />
            <div class="query-actions">
              <el-button type="primary" @click="executeQuery" :loading="analyzing">
                分析
              </el-button>
              <el-button @click="showExamples = true">示例</el-button>
            </div>
          </div>

          <div class="query-history" v-if="queryHistory.length > 0">
            <div class="history-title">查询历史</div>
            <div 
              v-for="(item, index) in queryHistory" 
              :key="index"
              class="history-item"
              @click="queryText = item.query"
            >
              <div class="history-query">{{ item.query }}</div>
              <div class="history-time">{{ formatTime(item.time) }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧：结果展示 -->
      <div class="result-panel">
        <el-card v-if="analysisResult">
          <template #header>
            <div class="card-header">
              <span>分析结果</span>
              <el-button text @click="exportResult" :icon="Download">导出</el-button>
            </div>
          </template>
          
          <div class="result-content">
            <!-- 数据摘要 -->
            <div class="result-summary" v-if="analysisResult.summary">
              <h4>数据摘要</h4>
              <div class="summary-text">{{ analysisResult.summary }}</div>
            </div>

            <!-- 图表展示 -->
            <div class="result-charts" v-if="analysisResult.charts">
              <div 
                v-for="(chart, index) in analysisResult.charts"
                :key="index"
                class="chart-item"
              >
                <div class="chart-title">{{ chart.title }}</div>
                <div class="chart-container" :id="`chart-${index}`"></div>
              </div>
            </div>

            <!-- 详细数据 -->
            <div class="result-table" v-if="analysisResult.data">
              <el-table :data="analysisResult.data" border>
                <el-table-column
                  v-for="(col, index) in analysisResult.columns"
                  :key="index"
                  :prop="col.prop"
                  :label="col.label"
                  :width="col.width"
                />
              </el-table>
            </div>

            <!-- AI建议 -->
            <div class="result-suggestions" v-if="analysisResult.suggestions">
              <h4>AI建议</h4>
              <ul>
                <li v-for="(suggestion, index) in analysisResult.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </div>
        </el-card>

        <el-empty v-else description="请输入查询内容开始分析" />
      </div>
    </div>

    <!-- 示例对话框 -->
    <el-dialog v-model="showExamples" title="查询示例" width="600px">
      <div class="examples-list">
        <div 
          v-for="example in queryExamples"
          :key="example.query"
          class="example-item"
          @click="queryText = example.query; showExamples = false"
        >
          <div class="example-label">{{ example.label }}</div>
          <div class="example-query">{{ example.query }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Delete, Download } from '@element-plus/icons-vue'
import { createAgentAi } from '@/uses/agentAi'

const queryText = ref('')
const analyzing = ref(false)
const showExamples = ref(false)
const analysisResult = ref(null)
const queryHistory = ref([])

const { sendMessage: sendWSMessage, connected } = createAgentAi()

const queryExamples = [
  {
    label: '销售趋势分析',
    query: '分析最近一个月的销售数据，包括每日销售趋势、热门商品和区域分布'
  },
  {
    label: '库存分析',
    query: '分析当前库存状况，找出库存积压超过30天的商品和缺货商品'
  },
  {
    label: '财务分析',
    query: '分析本月的财务状况，包括收入、支出、利润和现金流情况'
  },
  {
    label: '客户分析',
    query: '分析客户购买行为，包括高价值客户、流失客户和潜在客户'
  }
]

const executeQuery = async () => {
  if (!queryText.value.trim()) {
    ElMessage.warning('请输入查询内容')
    return
  }

  if (!connected.value) {
    ElMessage.warning('AI服务未连接，请稍候再试')
    return
  }

  analyzing.value = true
  
  // 保存到历史
  queryHistory.value.unshift({
    query: queryText.value,
    time: Date.now()
  })
  if (queryHistory.value.length > 10) {
    queryHistory.value = queryHistory.value.slice(0, 10)
  }

  try {
    // 发送查询请求
    sendWSMessage(`数据分析请求：${queryText.value}`)
    
    // 模拟分析结果（实际应该从WebSocket接收）
    setTimeout(() => {
      analysisResult.value = {
        summary: '根据您的查询，系统已分析相关数据并生成以下报告...',
        charts: [
          { title: '销售趋势图', type: 'line' },
          { title: '商品分布图', type: 'pie' }
        ],
        columns: [
          { prop: 'date', label: '日期', width: 120 },
          { prop: 'amount', label: '金额', width: 120 },
          { prop: 'count', label: '数量', width: 100 }
        ],
        data: [
          { date: '2024-01-01', amount: 10000, count: 50 },
          { date: '2024-01-02', amount: 12000, count: 60 }
        ],
        suggestions: [
          '建议关注销售增长较快的商品类别',
          '库存周转率需要提升',
          '可以考虑加大营销投入'
        ]
      }
      analyzing.value = false
    }, 2000)
  } catch (error) {
    ElMessage.error('分析失败，请重试')
    analyzing.value = false
  }
}

const clearHistory = () => {
  queryHistory.value = []
  ElMessage.success('已清空查询历史')
}

const exportResult = () => {
  ElMessage.info('导出功能开发中...')
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped lang="scss">
.ai-analysis-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    color: #303133;
  }
}

.analysis-container {
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 20px;
  height: calc(100vh - 120px);
}

.query-panel {
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.query-input {
  margin-bottom: 20px;
}

.query-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.query-history {
  border-top: 1px solid #e5e5e5;
  padding-top: 16px;
}

.history-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #303133;
}

.history-item {
  padding: 8px;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #409EFF;
    background: #f0f9ff;
  }
}

.history-query {
  font-size: 13px;
  color: #303133;
  margin-bottom: 4px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.result-panel {
  overflow-y: auto;
}

.result-content {
  .result-summary {
    margin-bottom: 24px;
    padding-bottom: 24px;
    border-bottom: 1px solid #e5e5e5;

    h4 {
      margin: 0 0 12px;
      color: #303133;
    }

    .summary-text {
      line-height: 1.8;
      color: #606266;
    }
  }

  .result-charts {
    margin-bottom: 24px;
  }

  .chart-item {
    margin-bottom: 24px;

    .chart-title {
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 12px;
      color: #303133;
    }

    .chart-container {
      height: 300px;
      background: #f5f5f5;
      border-radius: 6px;
    }
  }

  .result-suggestions {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid #e5e5e5;

    h4 {
      margin: 0 0 12px;
      color: #303133;
    }

    ul {
      margin: 0;
      padding-left: 20px;

      li {
        margin: 8px 0;
        color: #606266;
        line-height: 1.6;
      }
    }
  }
}

.examples-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.example-item {
  padding: 12px;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #409EFF;
    background: #f0f9ff;
  }
}

.example-label {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.example-query {
  font-size: 13px;
  color: #606266;
}
</style>
